import { EMClient } from "@/IM";
import { useImStore } from "@/stores/modules/im";
import { MESSAGE_TYPE } from "@/IM/constant/message.js";
import { ElMessage } from "element-plus";
export default function saveMsg(msg, type) {
  console.log(msg, type);
  //图片/视频类型原先使用组合url，现在直接miniCore中进行处理EMClient.Message.create(msgOptions)
  // url: "https://a1.easemob.com/" + str[0] + "/" + str[1] + "/chatfiles",
  // 			filePath: tempFilePaths[0],
  // 			fileType: 'image',
  // 			name: "file",
  // 			header: {
  // 			// "Content-Type": "multipart/form-data",
  // 			 'Content-Type': 'application/x-www-form-urlencoded',
  // 			Authorization: "Bearer " + token
  // 			},
  const imStore = useImStore();
  if (!imStore.chatWith) {
    return;
  }
  let msgOptions = {};
  if (type == MESSAGE_TYPE.TEXT) {
    msgOptions = {
      type,
      to: imStore.chatWith,
      chatType: "singleChat", //暂时只有单人聊天
      msg: msg,
      ext: {}
    };
  }
  if (type == MESSAGE_TYPE.IMAGE) {
    msg.type = type;
    msg.to = imStore.chatWith;
    msg.chatType = "singleChat";
    msgOptions = msg;
    if (msg.file.data.size / 1024 / 1024 > 10) {
      ElMessage.error("图片的文件大小不得大于10M");
      return;
    }
  }
  if (type == MESSAGE_TYPE.VIDEO) {
    msg.type = type;
    msg.to = imStore.chatWith;
    msg.chatType = "singleChat";
    msgOptions = msg;
    if (msg.file.data.size / 1024 / 1024 > 10) {
      ElMessage.error("视频的文件大小不得大于10M");
      return;
    }
  }
  if (type == MESSAGE_TYPE.FILE) {
    msg.type = type;
    msg.to = imStore.chatWith;
    msg.chatType = "singleChat";
    msgOptions = msg;
    if (msg.file.data.size / 1024 / 1024 > 10) {
      ElMessage.error("上传的文件大小不得大于10M");
      return;
    }
  }
  if (type == MESSAGE_TYPE.CUSTOM) {
    msg.type = type;
    msg.to = imStore.chatWith;
    msg.chatType = "singleChat";
    msg.ext = {};
    msgOptions = msg;
  }

  if (type == MESSAGE_TYPE.LOCATION) {
    console.log(111111, msg);
    let options = {
      chatType: "singleChat",
      type: "loc",
      to: imStore.chatWith,
      addr: msg.customExts.address,
      buildingName: msg.customExts.address,
      lat: msg.customExts.posX,
      lng: msg.customExts.posY
    };
    msgOptions = options;
  }
  const saveMsg = EMClient.Message.create(msgOptions);
  return EMClient.send(saveMsg)
    .then(result => {
      imStore.historyMessages[imStore.chatWith].push(result.message);
      imStore.clearReadMount(imStore.chatWith);
      imStore.getContacts();
      imStore.$patch({
        historyMessages: imStore.historyMessages,
        lastMessage: result.message.id
      });
      return true;
    })
    .catch(err => {
      if (err.type == 39) {
        ElMessage.error("尚未登录,无法发送消息");
      }
    });
}
